package com.cindata

import com.cindata.dictionary.*
import com.cindata.dimension.RiskDimension
import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['isAuthenticated()'])
@Transactional
class WorkflowInstanceUserController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def springSecurityService

    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond WorkflowInstanceUser.list(params), model:[workflowInstanceUserCount: WorkflowInstanceUser.count()]
    }

    def show(WorkflowInstanceUser workflowInstanceUser) {
        respond workflowInstanceUser
    }

    def create() 
    {
        params['targetUri'] = request.getHeader("referer")
        respond new WorkflowInstanceUser(params)
    }

    @Transactional
    def save(WorkflowInstanceUser workflowInstanceUser) {
        if (workflowInstanceUser == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (workflowInstanceUser.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond workflowInstanceUser.errors, view:'create'
            return
        }

        workflowInstanceUser.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'workflowInstanceUser.label', default: 'WorkflowInstanceUser'), workflowInstanceUser.id])
                redirect url: params['targetUri']
            }
            '*' { respond workflowInstanceUser, [status: CREATED] }
        }
    }

    def edit(WorkflowInstanceUser workflowInstanceUser) 
    {
        params['targetUri'] = request.getHeader("referer")
        respond workflowInstanceUser
    }

    @Transactional
    def update(WorkflowInstanceUser workflowInstanceUser) {
        if (workflowInstanceUser == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (workflowInstanceUser.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond workflowInstanceUser.errors, view:'edit'
            return
        }

        workflowInstanceUser.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'workflowInstanceUser.label', default: 'WorkflowInstanceUser'), workflowInstanceUser.id])
                redirect url: params['targetUri']
            }
            '*'{ respond workflowInstanceUser, [status: OK] }
        }
    }

    @Transactional
    def delete(WorkflowInstanceUser workflowInstanceUser) {

        def targetUri = request.getHeader("referer")
        if (workflowInstanceUser == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        workflowInstanceUser.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'workflowInstanceUser.label', default: 'WorkflowInstanceUser'), workflowInstanceUser.id])
                redirect url: targetUri
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'workflowInstanceUser.label', default: 'WorkflowInstanceUser'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }

    // 押品待办
    def collateralPending()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def externalId = params["externalId"]
        def sourceAddress = params["sourceAddress"]
        def workflow = params["workflow"]
        def buildingType = params["buildingType"]
        def sql = " "
        if (externalId && externalId != "") 
        {
            sql += " and stage.instance.collateral.externalId like '%${externalId}%' "
        }
        if (sourceAddress && sourceAddress != "") 
        {
            sql += " and stage.instance.collateral.estate.sourceAddress like '%${sourceAddress}%' "
        }
        if (workflow && workflow != "") 
        {
            sql += " and stage.instance.workflow.id = ${workflow} "
        }
        if (buildingType && buildingType != "") 
        {
            sql += " and stage.instance.collateral.estate.buildingType.id = ${buildingType} "
        }
        def user = User.findByUsername(springSecurityService.getPrincipal().username)
        def status = params['status']
        def  tempSql
        if (!status) 
        {
            tempSql = "select stage.instance.collateral.id, stage.instance.collateral.externalId, stage.instance.name, stage.instance.stage.name, stage.instance.status.name, stage.instance.createdDate, stage.instance.modifiedDate, stage.instance.collateral, stage.instance from WorkflowInstanceUser where user.id = ${user?.id} and stage.id = stage.instance.stage.id and stage.instance.status.name = 'Pending' "
        }
        else if (status == 'Already') 
        {
            tempSql = "select stage.instance.collateral.id, stage.instance.collateral.externalId, stage.instance.name, stage.instance.stage.name, stage.instance.status.name, stage.instance.createdDate, stage.instance.modifiedDate, stage.instance.collateral, stage.instance from WorkflowInstanceUser where user.id = ${user?.id} and stage.executionSequence < stage.instance.stage.executionSequence group by stage.instance.name "
        }
        tempSql+=sql
        tempSql+=" order by stage.instance.collateral.modifiedDate desc"

        def workflowInstanceUserList = WorkflowInstanceUser.executeQuery(tempSql,[max: max, offset: offset])
        def list = WorkflowInstanceUser.executeQuery(tempSql)
        def count = list?.size()
        respond workflowInstanceUserList, model: [workflowInstanceUserList: workflowInstanceUserList, workflowInstanceUserCount: count]
    }

    // 机构待办
    def accountPending()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def name = params["name"]
        def workflow = params["workflow"]
        def tempSql = " "
        if (name && name != "") 
        {
            tempSql += " and stage.instance.account.name like '%${name}%' "
        }
        if (workflow && workflow != "") 
        {
            tempSql += " and stage.instance.workflow.id = ${workflow} "
        }
        def user = User.findByUsername(springSecurityService.getPrincipal().username)
        def status = params['status']
        def sql
        if (!status)
        {
            sql = "select stage.instance.account.id, stage.instance.account.name, stage.instance.name, stage.instance.stage.name, stage.instance.status.name, stage.instance.createdDate, stage.instance.modifiedDate, stage.instance.account, stage.instance from WorkflowInstanceUser where user.id = ${user?.id} and stage.id = stage.instance.stage.id and stage.instance.status.name = 'Pending' "
        }
        else if (status == 'Already')
        {
            sql = "select stage.instance.account.id, stage.instance.account.name, stage.instance.name, stage.instance.stage.name, stage.instance.status.name, stage.instance.createdDate, stage.instance.modifiedDate, stage.instance.account, stage.instance from WorkflowInstanceUser where user.id = ${user?.id} and stage.executionSequence < stage.instance.stage.executionSequence group by stage.instance.name "
        }
        sql+=tempSql
        sql+=" order by stage.instance.account.modifiedDate desc"
        
        def workflowInstanceUserList = WorkflowInstanceUser.executeQuery(sql, [max: max, offset: offset])
        def list = WorkflowInstanceUser.executeQuery(sql)
        def count = list?.size()

        respond workflowInstanceUserList, model: [workflowInstanceUserList: workflowInstanceUserList, workflowInstanceUserCount: count],view: 'accountPending'
    }

    // 预警待办
    def riskWarningPending()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def serialNumber = params["serialNumber"]
        def sourceClassType = params["sourceClassType"]
        def workflow = params["workflow"]
        def warningType = params["warningType"]
        def tempSql = " "
        if (serialNumber && serialNumber != "") 
        {
            tempSql += " and stage.instance.riskWarning.serialNumber like '%${serialNumber}%' "
        }
        if (sourceClassType && sourceClassType != "") 
        {
            tempSql += " and stage.instance.riskWarning.sourceClassType = '${sourceClassType}' "
        }
        if (workflow && workflow != "") 
        {
            tempSql += " and stage.instance.workflow.id = ${workflow} "
        }
        if (warningType && warningType != "") 
        {
            tempSql += " and stage.instance.riskWarning.type.id = ${warningType} "
        }
        def user = User.findByUsername(springSecurityService.getPrincipal().username)
        def status = params['status']
        def sql
        if (!status)
        {
            sql = "select stage.instance.riskWarning.id, stage.instance.riskWarning.serialNumber, stage.instance.name, stage.instance.stage.name, stage.instance.status.name, stage.instance.createdDate, stage.instance.modifiedDate, stage.instance.riskWarning, stage.instance from WorkflowInstanceUser where user.id = ${user?.id} and stage.id = stage.instance.stage.id and stage.instance.status.name = 'Pending' "
        }
        else if (status == 'Already')
        {
            sql = "select stage.instance.riskWarning.id, stage.instance.riskWarning.serialNumber, stage.instance.name, stage.instance.stage.name, stage.instance.status.name, stage.instance.createdDate, stage.instance.modifiedDate, stage.instance.riskWarning, stage.instance from WorkflowInstanceUser where user.id = ${user?.id} and stage.executionSequence < stage.instance.stage.executionSequence group by stage.instance.name "
        }
        sql+=tempSql
        sql+=" order by stage.instance.riskWarning.modifiedDate desc"
        def workflowInstanceUserList = WorkflowInstanceUser.executeQuery(sql, [max: max, offset: offset])
        def list = WorkflowInstanceUser.executeQuery(sql)
        def count = list?.size()
        respond workflowInstanceUserList, model: [workflowInstanceUserList: workflowInstanceUserList, workflowInstanceUserCount: count],view: 'riskWarningPending'
    }

    // 不良资产包待办
    def abnormalMortgageBatchPending()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def name = params["name"]

        def estateQueryParam = new HashMap()
        def tempSql = " "

        if (name && name != "") {
            tempSql += " and stage.instance.abnormalMortgageBatch.name like '%${name}%' "
        }

        def user = User.findByUsername(springSecurityService.getPrincipal().username)
        def status = params['status']
        def sql = " "
        if (!status)
        {
            sql = "select stage.instance.abnormalMortgageBatch.id, stage.instance.abnormalMortgageBatch.name, stage.instance.name, stage.instance.stage.name, stage.instance.status.name, stage.instance.createdDate, stage.instance.modifiedDate, stage.instance.abnormalMortgageBatch, stage.instance from WorkflowInstanceUser where user.id = ${user?.id} and stage.id = stage.instance.stage.id and stage.instance.status.name = 'Pending' "
        }
        else if (status == 'Already')
        {
            sql = "select stage.instance.abnormalMortgageBatch.id, stage.instance.abnormalMortgageBatch.name, stage.instance.name, stage.instance.stage.name, stage.instance.status.name, stage.instance.createdDate, stage.instance.modifiedDate, stage.instance.abnormalMortgageBatch, stage.instance from WorkflowInstanceUser where user.id = ${user?.id} and stage.executionSequence < stage.instance.stage.executionSequence group by stage.instance.name "
        }
        sql+=tempSql
        sql+=" order by stage.instance.abnormalMortgageBatch.modifiedDate desc"

        def workflowInstanceUserList = WorkflowInstanceUser.executeQuery(sql, [max: max, offset: offset])
        def list = WorkflowInstanceUser.executeQuery(sql)
        def count = list?.size()

        respond workflowInstanceUserList, model: [workflowInstanceUserList: workflowInstanceUserList, workflowInstanceUserCount: count],view: 'abnormalMortgageBatchPending'
    }
}
